package com.awspaass.user.apps.businesscar;

import com.actionsoft.bpms.commons.database.ColumnMapRowMapper;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.bind.annotation.Controller;
import com.actionsoft.bpms.server.bind.annotation.Mapping;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.awspaas.user.apps.shhtaerospaceindustrial.sms.SmsUtil;
import com.awspaas.user.apps.shhtaerospaceindustrial.util.CoreUtil;

import java.util.List;
import java.util.Map;

@Controller
public class AppCmdBusinessUser {
	/**
	 * 用户获取进行中的行程任务单
	 * 
	 * @param uc
	 * @param roleType
	 * @param bDate
	 * @param eDate
	 * @param page
	 * @param pageCount
	 * @param taskType
	 * @return
	 */
	@Mapping("com.awspaas.user.apps.businesscar_userGetMission")
	public String userGetMission(UserContext uc, int roleType, String bDate, String eDate, int page, int pageCount,
			int taskType) {
		JSONObject returnData = new JSONObject();
		try {
			String userId = uc.getUID();
			String sid = uc.getSessionId();
			if (page < 1) {
				returnData.put("status", "1");
				returnData.put("message", "请传入大于等于1的起始页！");
				return returnData.toString();
			}
			// 获取起始条数和结束条数
			int start = (page - 1) * pageCount + 1;
			int end = page * pageCount;
			String timePeriod = "";// 行车确认是否查全部
			if (!bDate.equals("") && !eDate.equals("")) {
				timePeriod = "AND B.USEDATE >= TO_DATE('" + bDate + "','yyyy-MM-dd') AND B.USEDATE <= TO_DATE('" + eDate
						+ "','yyyy-MM-dd')";
			}

			String missionQuerySql = "SELECT * FROM (SELECT TT.*, ROWNUM AS rowno FROM (SELECT (CASE WHEN B.SJLXFS IS NOT NULL THEN CONCAT("
					+ "CONCAT(CONCAT(B.SJXM,'('),B.SJLXFS),')') ELSE CONCAT(B.SJXM,B.SJLXFS) END) SJXX,B.USEDATE,B.CFSJ,B.FHSJ,B.VEHICLETYPE,B.CPH,"
					+ "(CASE WHEN B.MISSIONSTATUS=0 THEN '未派单' WHEN B.MISSIONSTATUS=1 THEN '已派单' WHEN B.MISSIONSTATUS=2 THEN '已接单' WHEN B.MISSIONSTATUS"
					+ "=3 THEN '待结算' WHEN B.MISSIONSTATUS=4 THEN '待确认' WHEN B.MISSIONSTATUS=5 THEN '已确认' WHEN B.MISSIONSTATUS=6 THEN '已取消' ELSE '' END) MISSIONSTATUS,A.PROCESSINSTID,A.ID,'1' RWZT FROM BO_EU_YBBZUSECAR_MISSION B LEFT JOIN WFC_TASK A ON "
					+ "A.PROCESSINSTID = B.BINDID WHERE B.APPLYUID = '" + userId + "' " + timePeriod
					+ " AND B.MISSIONSTATUS IN (1,2,3,4) AND A.DISPATCHID IS NOT NULL AND A.TASKTITLE NOT LIKE '%空标题%'"
					+ " ORDER BY B.USEDATE) TT WHERE ROWNUM <= " + end + ") table_alias WHERE table_alias.rowno >= "
					+ start + "";
			System.out.println(missionQuerySql);

			String portalUrl = SDK.getPortalAPI().getPortalUrl();
			JSONArray jsonMission = new JSONArray();

			if (!missionQuerySql.equals("")) {
				List<Map<String, Object>> missionInfoList = DBSql.query(missionQuerySql, new ColumnMapRowMapper(),
						new Object[] {});
				if (missionInfoList == null || missionInfoList.isEmpty()) {
					returnData.put("status", "0");
					returnData.put("jsonMission", jsonMission);
				} else {
					for (int i = 0; i < missionInfoList.size(); i++) {
						JSONObject jsonMissionOBJ = new JSONObject();
						Map<String, Object> missionMap = missionInfoList.get(i);
						String useDate = CoreUtil.objToStr(missionMap.get("USEDATE"));
						String driverInfo = CoreUtil.objToStr(missionMap.get("SJXX"));// 司机姓名（联系方式）
						String startUseTime = CoreUtil.objToStr(missionMap.get("CFSJ"));// 出车时间
						String endUseTime = CoreUtil.objToStr(missionMap.get("FHSJ"));// 返回时间
						if (!startUseTime.equals("")) {
							startUseTime = startUseTime.substring(0, 16);
						}
						if (!endUseTime.equals("")) {
							endUseTime = endUseTime.substring(0, 16);
						}

						String carNo = CoreUtil.objToStr(missionMap.get("CPH"));

						String carType = CoreUtil.objToStr(missionMap.get("VEHICLETYPE"));// 车型
						String missionStatus = CoreUtil.objToStr(missionMap.get("MISSIONSTATUS"));// 状态
						String processInstId = CoreUtil.objToStr(missionMap.get("PROCESSINSTID"));// 流程实例ID
						String taskInstId = CoreUtil.objToStr(missionMap.get("ID"));// 任务实例Id
						String rwzt = CoreUtil.objToStr(missionMap.get("RWZT"));// 1：待办|2：已办

						String url = portalUrl + "/r/w?sid=" + sid
								+ "&cmd=CLIENT_BPM_FORM_MAIN_PAGE_OPEN&processInstId=" + processInstId
								+ "&openState=1&taskInstId=" + taskInstId + "&displayToolbar=true";
						jsonMissionOBJ.put("driverInfo", driverInfo);
						jsonMissionOBJ.put("startUseTime", startUseTime);
						jsonMissionOBJ.put("endUseTime", endUseTime);
						carType = SDK.getDictAPI().getValue("com.awspaas.user.apps.shhtaerospaceindustrial",
								"shcartype", carType, "CNNAME");
						jsonMissionOBJ.put("carType", carType);
						jsonMissionOBJ.put("missionStatus", missionStatus);
						jsonMissionOBJ.put("rwzt", rwzt);
						jsonMissionOBJ.put("processInstId", processInstId);
						jsonMissionOBJ.put("url", url);
						jsonMissionOBJ.put("carNo",carNo);
						jsonMissionOBJ.put("useDate", useDate);
						jsonMission.add(jsonMissionOBJ);
					}
				}

			}
			returnData.put("status", "0");
			returnData.put("jsonMission", jsonMission);
		} catch (Exception e) {

		}
		return returnData.toString();
	}

	/**
	 * 用户取消出车前30分钟的任务单
	 * 
	 * @param ids
	 * @param processInstId
	 * @param id
	 * @param uc
	 * @return
	 */
	@Mapping("com.awspaas.user.apps.businesscar__userCancelMission")
	public String userCancelMission(String ids, String processInstId, String id, UserContext uc) {
		JSONObject returnData = new JSONObject();
		String userid = uc.getUID();

		String queryInfoSql = "select a.RESOURCETASKFPID,a.USEDATE, a.CPH,a.SJXM, a.SJLXFS,a.bindid,a.SJZH,a.APPLYUSERNAME,a.APPLYUID,a.APPLYUSERMOBILE,a.USEDATE,a.CPH,a.VEHICLETYPE,a.CONTACTPERSON,a.CONTACTPHONE from BO_EU_YBBZUSECAR_MISSION a WHERE BINDID = "
				+ "'" + processInstId + "'";
		String BINDID = CoreUtil.objToStr(DBSql.getString(queryInfoSql, "BINDID"));
		String APPLYUSERNAME = CoreUtil.objToStr(DBSql.getString(queryInfoSql, "APPLYUSERNAME"));// 预定人姓名
		String APPLYUSERMOBILE = CoreUtil.objToStr(DBSql.getString(queryInfoSql, "APPLYUSERMOBILE"));
		String SJXM = CoreUtil.objToStr(DBSql.getString(queryInfoSql, "SJXM"));
		String SJLXFS = CoreUtil.objToStr(DBSql.getString(queryInfoSql, "SJLXFS"));
		String CONTACTPERSON = CoreUtil.objToStr(DBSql.getString(queryInfoSql, "CONTACTPERSON"));
		String CONTACTPHONE = CoreUtil.objToStr(DBSql.getString(queryInfoSql, "CONTACTPHONE"));
		String USEDATE = CoreUtil.objToStr(DBSql.getString(queryInfoSql, "USEDATE"));
		String CPH = CoreUtil.objToStr(DBSql.getString(queryInfoSql, "CPH"));
		String RESOURCETASKFPID = CoreUtil.objToStr(DBSql.getString(queryInfoSql, "RESOURCETASKFPID"));
		String message_user = "{'applyUserName':'" + APPLYUSERNAME + "','udate':'" + USEDATE + "','cph':'" + CPH + "'}";
		String message_driver = "{'applyUserName':'" + SJXM + "','udate':'" + USEDATE + "','cph':'" + CPH + "'}";
//		String message_driver = "{'applyUserName':'" + SJXM + "','udate':'" + UDATE+ "','guestName':'" + APPLYUSERNAME + "','cph':'" + CPH + "'}";
		SmsUtil sms = new SmsUtil();

		String updateAssignSql = "update BO_EU_YBOFFICEUSECAR_DS set ZT='2',MISSIONSTATUS='6' where id ='"
				+ RESOURCETASKFPID + "'";
		String updateMissionSql = "update BO_EU_YBBZUSECAR_MISSION set MISSIONSTATUS='6' where bindid='" + BINDID
				+ "'";
		System.out.println(updateAssignSql);
		DBSql.update(updateAssignSql);// 修改上航_车辆任务分配状态
		DBSql.update(updateMissionSql);
		try {
			System.out.println("准备终止流程！流程号:" + BINDID + "用户ID:" + userid);
			SDK.getProcessAPI().terminateById(BINDID, userid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			SmsUtil.sendSms(APPLYUSERMOBILE, "SMS_228016523", message_user);
			SmsUtil.sendSms(SJLXFS, "SMS_228116397", message_driver);
//			SmsUtil.sendSms(SJLXFS, "SMS_229641290", message_driver);
			//sms.sendSms("15221751780", "SMS_228116397", message_driver);

		} catch (Exception e) {
			e.printStackTrace();
		}

		if (!CONTACTPERSON.equals("")) {
			message_user = "{'applyUserName':'" + CONTACTPERSON + "','udate':'" + USEDATE + "','cph':'" + CPH + "'}";

			try {
				SmsUtil.sendSms(CONTACTPHONE, "SMS_228016523", message_user);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		returnData.put("status", "0");
		returnData.put("message", "取消成功！");
		return returnData.toString();
	}

}
